/*******************************************************************************
 * Copyright (c) 2006 CEA List.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     CEA List - initial API and implementation
 *******************************************************************************/
package com.cea.papyrus.core.commands.connection;

import org.eclipse.draw2d.geometry.Point;

import com.cea.papyrus.diagraminterchange2.di2.GraphEdge;

/**
 * 
 */
public class MoveBendpointCommand extends BendpointCommandBase {
  
  /**
   * 
   */
  private GraphEdge connection;
  
  /**
   * 
   */
  private Point oldLocation, newLocation;
  
  /**
   * 
   */
  private int index;

  /**
   * 
   */
  private SegmentAnchors seg1;
  
  /**
   * 
   */
  private SegmentAnchors seg2;
  
  
  /**
   * 
   */
  @Override
public void execute() {
	  // Save adjacent segments
	  // save anchors of old segments (index-1)
	  Point src = getSegmentSourceLocation(connection, index);
	  Point target = getSegmentTargetLocation(connection, index+1);
	  Point middle = getSegmentTargetLocation(connection, index);
	  // create two saved segments using the midpoint as separator
	  seg1 = new SegmentAnchors( src, middle, connection.getAnchorage());
	  seg2 = new SegmentAnchors( middle, target, connection.getAnchorage());
	  // move both segments
	  seg1.moveTargetEnd(newLocation);
	  seg2.moveSourceEnd(newLocation);
	  //replace bendpoint
    oldLocation = (Point) connection.getWaypoints().remove(index);
    connection.getWaypoints().add(index, newLocation);
  }

  /**
   * Redo the command.
   */
  public void redo()
  {
	  // move both segments
	  seg1.moveTargetEnd(newLocation);
	  seg2.moveSourceEnd(newLocation);
	  //replace bendpoint
    oldLocation = (Point) connection.getWaypoints().remove(index);
    connection.getWaypoints().add(index, newLocation);
  }
  
  
  /**
   * 
   * 
   * @param model 
   */
  public void setConnectionModel(Object model) {
    connection = (GraphEdge) model;
  }

  /**
   * 
   * 
   * @param i 
   */
  public void setIndex(int i) {
    index = i;
  }

  /**
   * 
   * 
   * @param point 
   */
  public void setNewLocation(Point point) {
    newLocation = point;
  }

  
  /**
   * 
   */
  @Override
public void undo() {
	  
	    seg1.restoreAnchors();
	    seg2.restoreAnchors();
 
	connection.getWaypoints().remove(index);
    connection.getWaypoints().add(index, oldLocation);
  }

}
